﻿using AutoMapper;
using B.S.Base.Write.API.Application.Command;
using MediatR;
using Microsoft.EntityFrameworkCore;
using WEBAPI.Damoin;
using WEBAPI.ErroeCode;
using WEBAPI.Indaseture.Infasetures;

namespace B.S.Base.Write.API.Application.CommandHandLer
{
    public class UpdateAccountCommandHandLer : IRequestHandler<UpdateAccountCommand, APIResult<int>>
    {
        IBaseRepostiy<AccountModel> _accountModel;
        IMapper _mapper;

        public UpdateAccountCommandHandLer(IBaseRepostiy<AccountModel> accountModel, IMapper mapper)
        {
            _accountModel = accountModel;
            _mapper = mapper;
        }

        public async Task<APIResult<int>> Handle(UpdateAccountCommand request, CancellationToken cancellationToken)
        {
            var entity = await _accountModel.GetAll().FirstOrDefaultAsync(x => x.AccountId == request.AccountId && x.IsDeleted == false);
            var query = await _accountModel.GetAll().FirstOrDefaultAsync(x => x.AccountName == request.AccountName && x.AccountId != request.AccountId && x.IsDeleted == false);
            if (query != null)
            {
                return new APIResult<int>
                {
                    Code = ResultCode.Fail,
                    Message = "用户重复"
                };
            }

            // 只更新需要变更的字段
            entity.AccountName = request.AccountName;
            entity.Sex = request.Sex;
            entity.Province = request.Province;
            entity.Market = request.Market;
            entity.County = request.County;
            entity.Address = request.Address;
            entity.UpdateUserName = request.UpdateUserName;
            entity.UpdateUserTime = DateTime.Now;
            // entity.Pwd 不变

            await _accountModel.Update(entity);

            return new APIResult<int>
            {
                Code = ResultCode.Ok,
                Data = 1,
                Message = "修改成功"
            };
        }
    }
}
